package com.hmall.hmallapi.config;

import com.hmall.hmallapi.fallback.CartServiceFallBack;
import com.hmall.hmallapi.fallback.ItemServiceFallBack;
import com.hmall.hmallapi.fallback.OrderServiceFallBack;
import com.hmall.hmallapi.fallback.UserServiceFallBack;
import com.hmall.hmallcommon.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogLevel() {
        return Logger.Level.BASIC;
    }

    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 获取登录用户
                Long userId = UserContext.getUser();
                if (userId == null) {
                    // 如果为空则直接跳过
                    return;
                }
                // 如果不为空则放入请求头中，传递给下游微服务
                template.header("user-info", userId.toString());
            }
        };
    }

    @Bean
    public CartServiceFallBack cartServiceFallBack() {
        return new CartServiceFallBack();
    }

    @Bean
    public ItemServiceFallBack itemServiceFallback() {
        return new ItemServiceFallBack();
    }

    @Bean
    public OrderServiceFallBack orderServiceFallBack() {
        return new OrderServiceFallBack();
    }

    @Bean
    public UserServiceFallBack userServiceFallBack() {
        return new UserServiceFallBack();
    }
}
